package datatype;

import org.junit.Test;

import java.util.Iterator;

/**
 * @author DuJiabao
 * @create 2020-12-28 22:53
 */
public class LinkedListBag<Item> implements Iterable<Item> {
    private int count = 0;
    private Node<Item> head;
    private Node<Item> tail;


    @Test
    public void test() {
        LinkedListBag<Integer> linkedListBag = new LinkedListBag<Integer>();
        System.out.println(linkedListBag.isEmpty());
        linkedListBag.add(100);
        linkedListBag.add(20);
        linkedListBag.add(130);
        System.out.println(linkedListBag.isEmpty());
        System.out.println(linkedListBag.size());
        Iterator<Integer> iterator = linkedListBag.iterator();
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());
    }

    public LinkedListBag() {
    }

    public void add(Item item) {
        Node<Item> node = new Node<Item>(item, null);
        if (count == 0) {
            head = node;
        } else {
            tail.setNext(node);
        }
        tail = node;
        count++;
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public int size() {
        return count;
    }

    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {
        private Node<Item> current = head;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.getItem();
            current = current.getNext();
            return item;
        }
    }
}
